import React, { useState, useEffect } from 'react';
import { Website } from '../types/website';
import Modal from '@/components/update/Modal';

const WebsiteList: React.FC = () => {
  const [websites, setWebsites] = useState<Website[]>([
    {
      id: '1',
      name: 'OpenAI API',
      url: 'https://models.openapi.cn/auth',
      callbackUrl: /^https:\/\/(.*\.)?openapi\.cn\/?$/,
      isIntegrated: false,
    },
    {
      id: '2',
      name: 'CSDN',
      url: 'https://passport.csdn.net/login',
      callbackUrl: /^https:\/\/(.*\.)?csdn\.net\/?$/,
      isIntegrated: false,
    },
    {
      id: '3',
      name: '知乎',
      url: 'https://www.zhihu.com/signin',
      callbackUrl: /^https:\/\/(.*\.)?zhihu\.com\/?$/,
      isIntegrated: false,
    },
    {
      id: '4',
      name: '简书',
      url: 'https://www.jianshu.com/sign_in',
      callbackUrl: /^https:\/\/(.*\.)?jianshu\.com\/?$/,
      isIntegrated: false,
    },
  ]);
  
  const [showCookieModal, setShowCookieModal] = useState(false);
  const [selectedWebsiteId, setSelectedWebsiteId] = useState<string | null>(null);

  // 从本地存储加载 cookie 状态
  useEffect(() => {
    const loadCookieStatus = async () => {
      try {
        for (const website of websites) {
          const result = await window.ipcRenderer.invoke('load-cookies', website.id);
          if (result.success && result.cookies && result.cookies.length > 0) {
            website.isIntegrated = true
          }
        }
        setWebsites([...websites])
      } catch (error) {
        console.error('加载 cookie 状态失败', error);
      }
    };
    
    loadCookieStatus();
    
    // 添加事件监听器，处理网站集成成功事件
    const handleWebsiteIntegrated = (_: any, data: {id: string}) => {
      setWebsites(prev => {
        return prev.map(website => {
          if (website.id === data.id) {
            return {...website, isIntegrated: true};
          }
          return website;
        });
      });
    };
    
    // 注册事件监听器
    window.ipcRenderer.on('website-integrated', handleWebsiteIntegrated);
    
    // 清理函数，组件卸载时移除事件监听器
    return () => {
      window.ipcRenderer.off('website-integrated', handleWebsiteIntegrated);
    };
  }, []);

  const handleIntegrate = async (website: Website) => {
    const result = await window.ipcRenderer.invoke('open-browser', website.url, true, website.id, website.callbackUrl);
    
    if (!result.success) {
      console.error(`打开网站 ${website.name} 失败:`, result.error);
      return;
    }
  };

  const handleOpenBrowser = async (website: Website) => {
    if(!website.isIntegrated){
      console.error(`网站 ${website.name} 未集成`);
      return;
    }
    const result = await window.ipcRenderer.invoke('open-browser', website.url, false, website.id, website.callbackUrl);
    if (!result.success) {
      console.error(`打开网站 ${website.name} 失败:`, result.error);
      return;
    }
  }

  const handleViewCookies = (website: Website) => {
    if(!website.isIntegrated){
      console.error(`网站 ${website.name} 未集成，没有可查看的Cookie`);
      return;
    }
    setSelectedWebsiteId(website.id);
    setShowCookieModal(true);
  }

  const handleClearCookies = async (website: Website) => {
    if(!website.isIntegrated){
      console.error(`网站 ${website.name} 未集成，没有Cookie可清除`);
      return;
    }
    
    try {
      const result = await window.ipcRenderer.invoke('clear-cookies', website.id);
      if (result.success) {
        setWebsites(prev => {
          return prev.map(w => {
            if (w.id === website.id) {
              return {...w, isIntegrated: false};
            }
            return w;
          });
        });
      } else {
        console.error(`清除网站 ${website.name} 的Cookie失败:`, result.error);
      }
    } catch (error) {
      console.error(`清除网站 ${website.name} 的Cookie时发生错误:`, error);
    }
  }

  return (
    <div className="p-4">
      <h2 className="text-2xl font-bold mb-4">网站集成列表</h2>
      <div className="space-y-4">
        {websites.map((website) => (
          <div key={website.id} className="flex items-center justify-between p-4 bg-white rounded-lg shadow">
            <div>
              <h3 className="text-lg font-semibold">{website.name}</h3>
              <p className="text-gray-600">{website.url}</p>
            </div>
            <div className="flex items-center space-x-4">
              <span className={`px-3 py-1 rounded-full text-sm ${
                website.isIntegrated 
                  ? 'bg-green-100 text-green-800' 
                  : 'bg-gray-100 text-gray-800'
              }`}>
                {website.isIntegrated ? '已集成' : '未集成'}
              </span>
              <button
                onClick={() => handleIntegrate(website)}
                className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors"
              >
                {website.isIntegrated ? '重新集成' : '集成'}
              </button>
              <button
                onClick={() => handleOpenBrowser(website)}
                disabled={!website.isIntegrated}
                className={`px-4 py-2 ${
                  website.isIntegrated 
                    ? 'bg-blue-500 text-white hover:bg-blue-600' 
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                } rounded transition-colors`}
              >
                打开
              </button>
              <button
                onClick={() => handleViewCookies(website)}
                disabled={!website.isIntegrated}
                className={`px-4 py-2 ${
                  website.isIntegrated 
                    ? 'bg-blue-500 text-white hover:bg-blue-600' 
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                } rounded transition-colors`}
              >
                查看Cookie
              </button>
              <button
                onClick={() => handleClearCookies(website)}
                disabled={!website.isIntegrated}
                className={`px-4 py-2 ${
                  website.isIntegrated 
                    ? 'bg-red-500 text-white hover:bg-red-600' 
                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                } rounded transition-colors`}
              >
                清除Cookie
              </button>
            </div>
          </div>
        ))}
      </div>

      {showCookieModal && (
        <Modal 
          title="Cookie 查看"
          width={800}
          onCancel={() => setShowCookieModal(false)}
          onOk={() => setShowCookieModal(false)}
          okText="关闭"
          cancelText="取消"
          open={showCookieModal}
        >
          <div style={{ maxHeight: '500px', overflowY: 'auto' }}>
            <CookieViewerWrapper websiteId={selectedWebsiteId} />
          </div>
        </Modal>
      )}
    </div>
  );
};

// CookieViewer包装组件，用于在Modal中显示指定网站的Cookie
const CookieViewerWrapper: React.FC<{websiteId: string | null}> = ({ websiteId }) => {
  const [cookies, setCookies] = useState<any[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadCookies = async () => {
      if (!websiteId) return;
      
      try {
        setError(null);
        const result = await window.ipcRenderer.invoke('load-cookies', websiteId);
        if (result.success) {
          setCookies(result.cookies || []);
        } else {
          setError(result.error || '加载Cookie失败');
        }
      } catch (err) {
        setError('加载Cookie失败');
      }
    };
    
    loadCookies();
  }, [websiteId]);

  return (
    <div className="cookie-viewer">
      <h3 className="text-lg font-semibold mb-4">网站ID: {websiteId}</h3>
      
      {error && <div className="bg-red-100 text-red-800 p-3 rounded mb-4">{error}</div>}
      
      {cookies.length > 0 ? (
        <div className="overflow-x-auto">
          <table className="w-full border-collapse">
            <thead>
              <tr className="bg-gray-100">
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">名称</th>
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">值</th>
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">域名</th>
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">路径</th>
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">过期时间</th>
                <th className="p-2 text-left border-b sticky top-0 bg-gray-100">安全</th>
              </tr>
            </thead>
            <tbody>
              {cookies.map((cookie, index) => (
                <tr key={index} className="hover:bg-gray-50">
                  <td className="p-2 border-b">{cookie.name}</td>
                  <td className="p-2 border-b">
                    <div className="max-w-xs overflow-hidden text-ellipsis" title={cookie.value}>
                      {cookie.value.length > 30 ? `${cookie.value.substring(0, 30)}...` : cookie.value}
                    </div>
                  </td>
                  <td className="p-2 border-b">{cookie.domain}</td>
                  <td className="p-2 border-b">{cookie.path}</td>
                  <td className="p-2 border-b">{cookie.expires ? new Date(cookie.expires * 1000).toLocaleString() : '会话'}</td>
                  <td className="p-2 border-b">{cookie.secure ? '是' : '否'}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="text-gray-500">没有Cookie数据</div>
      )}
    </div>
  );
};

export default WebsiteList; 